﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Windows.Media.Control;

namespace SocketService
{
    public class WindowsHelper
    {
        // -------------------- Windows API 常量 --------------------
        private const int WM_GETICON = 0x007F;
        private const int ICON_BIG = 1;
        private const int GCL_HICON = -14;
        private const int GCLP_HICONSM = -34;

        // -------------------- 导入 Windows API --------------------
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", SetLastError = true)]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern uint GetDpiForWindow(IntPtr hwnd);

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern int ExtractIconEx(string lpszFile, int nIconIndex, out IntPtr phiconLarge, out IntPtr phiconSmall, uint nIcons);

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern int ExtractIconEx(string lpszFile, int nIconIndex, IntPtr[] phiconLarge, IntPtr[] phiconSmall, int nIcons);

        // -------------------- 媒体播放 --------------------
        public static void GetCurrentMediaInfo()
        {
            var sessionManager = GlobalSystemMediaTransportControlsSessionManager.RequestAsync().GetAwaiter().GetResult();
            var currentSession = sessionManager.GetCurrentSession();

            if (currentSession != null)
            {
                var mediaProperties = currentSession.TryGetMediaPropertiesAsync().GetAwaiter().GetResult();
                var playbackInfo = currentSession.GetPlaybackInfo();

                Console.WriteLine($"正在播放: {mediaProperties.Title} - {mediaProperties.Artist}");
                Console.WriteLine($"播放状态: {playbackInfo.PlaybackStatus}");
            }
            else
            {
                Console.WriteLine("当前没有媒体播放");
            }
        }

        // -------------------- 获取当前活动窗口信息（含 EXE 路径） --------------------
        public static (string Title, string ProcessName, string ExePath) GetActiveWindowInfoWithPath()
        {
            IntPtr hwnd = GetForegroundWindow();
            if (hwnd == IntPtr.Zero) return (null, null, null);

            GetWindowThreadProcessId(hwnd, out uint pid);

            try
            {
                var process = Process.GetProcessById((int)pid);
                string title = process.MainWindowTitle;
                string processName = process.ProcessName;
                string exePath = process.MainModule.FileName; // 获取 EXE 路径
                return (title, processName, exePath);
            }
            catch
            {
                return (null, null, null); // 可能没有权限访问系统进程
            }
        }

        // -------------------- 从 EXE 获取高分辨率图标 --------------------
        public static Icon GetAppIcon(string exePath)
        {
            if (!File.Exists(exePath)) return null;

            // 尝试从 EXE 提取大图标
            IntPtr[] largeIcons = new IntPtr[1];
            IntPtr[] smallIcons = new IntPtr[1];
            ExtractIconEx(exePath, 0, largeIcons, smallIcons, 1);

            if (largeIcons[0] != IntPtr.Zero)
            {
                return Icon.FromHandle(largeIcons[0]);
            }

            // 保底方案：使用默认方法
            return Icon.ExtractAssociatedIcon(exePath);
        }

        // -------------------- 将 Icon 转为 Base64 PNG --------------------
        public static string IconToBase64(Icon icon, int size = 256)
        {
            if (icon == null) return null;

            // 转 Bitmap 并缩放到指定尺寸
            using (Bitmap bmp = new Bitmap(icon.ToBitmap(), new Size(size, size)))
            using (MemoryStream ms = new MemoryStream())
            {
                bmp.Save(ms, ImageFormat.Png);
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        // -------------------- 获取当前活动窗口的图标（优先高分辨率） --------------------
        public static Icon GetHighQualityWindowIcon(IntPtr hWnd)
        {
            // 尝试获取窗口大图标
            IntPtr hIcon = SendMessage(hWnd, WM_GETICON, ICON_BIG, IntPtr.Zero);

            // 如果失败，尝试获取类图标
            if (hIcon == IntPtr.Zero)
                hIcon = GetClassLongPtr(hWnd, GCL_HICON);

            // 获取失败则从EXE文件提取
            if (hIcon == IntPtr.Zero)
                return GetExeHighQualityIcon(hWnd);

            // 克隆图标，避免原始资源被释放
            using (Icon tempIcon = Icon.FromHandle(hIcon))
            {
                return new Icon(tempIcon, GetOptimalIconSize(hWnd));
            }
        }

        private static Size GetOptimalIconSize(IntPtr hWnd)
        {
            // 根据 DPI 计算最佳图标尺寸
            uint dpi = GetDpiForWindow(hWnd);
            int baseSize = 256; // 默认优先大尺寸
            int scaledSize = (int)(baseSize * dpi / 96);

            // 常用标准尺寸
            int[] standardSizes = { 256, 128, 64, 48, 32, 16 };
            foreach (int size in standardSizes)
            {
                if (scaledSize >= size) return new Size(size, size);
            }
            return new Size(32, 32);
        }

        private static Icon GetExeHighQualityIcon(IntPtr hWnd)
        {
            // 获取 EXE 路径
            GetWindowThreadProcessId(hWnd, out uint processId);
            string exePath = Process.GetProcessById((int)processId).MainModule.FileName;

            // 尝试提取最大图标
            ExtractIconEx(exePath, 0, out IntPtr largeIcon, out IntPtr _, 1);
            if (largeIcon != IntPtr.Zero)
            {
                using (Icon tempIcon = Icon.FromHandle(largeIcon))
                {
                    return new Icon(tempIcon, GetOptimalIconSize(hWnd));
                }
            }
            return Icon.ExtractAssociatedIcon(exePath);
        }
    }
}
